package org.zjt.flink.wordcount;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;
import org.zjt.flink.wordcount.util.WordCountData;

import java.util.Objects;

/**
 * Description:   过滤器
 *
 * @author juntao.zhang
 * Date: 2018-09-29 下午2:29
 * @see
 */
public class StopWordFilterWordCount {


    public static void main(String[] args) throws Exception {
        final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        DataSource<String> stringDataSource = env.fromElements(WordCountData.WORDS);

        AggregateOperator<Tuple2<String, Integer>> sum = stringDataSource.flatMap(new LineSplitter()).filter(new StopWordFilterFunction()).groupBy(0).sum(1);

        sum.print();
    }


    public static final class LineSplitter implements FlatMapFunction<String, Tuple2<String, Integer>> {
        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) {

            String[] tokens = s.toLowerCase().split("\\W+");

            for (String token: tokens) {
                if (token.length() > 0) {
                    collector.collect(new Tuple2(token, 1));
                }
            }
        }
    }


    public static final class StopWordFilterFunction implements FilterFunction<Tuple2<String, Integer>> {

        @Override
        public boolean filter(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
            for (int i = 0; i < stringIntegerTuple2.getArity(); i++) {
                Object field = stringIntegerTuple2.getField(i);
                System.out.println("field:" +field);
                if (Objects.isNull(field) || Objects.equals("is",field) || Objects.equals("was",field) || Objects.equals("are",field)){
                    return false;
                }
            }
            return true;
        }
    }
}
